#include "RoundSummaryView.h"
#include "curl/curl.h"
#include "NetworkManager.h"
#include "JsonObject.h"
#include "PlayScene.h"
#include "GameManager.h"

USING_NS_CC;

CCScene* RoundSummaryView::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();
    
    // 'layer' is an autorelease object
    RoundSummaryView *layer = RoundSummaryView::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool RoundSummaryView::init()
{
    if ( !CCLayer::init() )
    {
        return false;
    }

	CCSize winSize = CCDirector::sharedDirector()->getWinSize();

    CCSprite* pBG = CCSprite::create("game_bg.png");
	pBG->setAnchorPoint(CCPoint(0.5f, 0.5f));
	pBG->setPosition(CCPoint(winSize.width / 2, winSize.height / 2));
	this->addChild(pBG);

	CCMenu* pMenu = CCMenu::create();
	this->addChild(pMenu);

	mPlayButton = CCMenuItemImage::create("new_game_cell_active.png", "new_game_cell_inactive.png", this, menu_selector(RoundSummaryView::playGameCallback));
	mPlayButton->setScale(0.5f);
	mPlayButton->setPosition(CCPoint(100.0f, -200.0f));

	pMenu->addChild(mPlayButton);

	CCLabelTTF* pNewLabel = CCLabelTTF::create("Play", "Arial", 40.0f);
	pNewLabel->setPosition(CCPoint(150.0f, 30.0f));
	mPlayButton->addChild(pNewLabel, 0, 0);

	mPlayButton->setColor(ccGRAY);
	mPlayButton->setEnabled(false);

	CCLabelTTF* mLabelMyName = CCLabelTTF::create("Me", "Arial", 30.0f);
	mLabelMyName->setPosition(CCPoint(winSize.width / 2 - 100, winSize.height / 2 + 180));
	this->addChild(mLabelMyName);

	CCLabelTTF* mLabelOpponentName = CCLabelTTF::create("Opponent", "Arial", 30.0f);
	mLabelOpponentName->setPosition(CCPoint(winSize.width / 2 + 80, winSize.height / 2 + 180));
	this->addChild(mLabelOpponentName);

	CCLabelTTF* mLabelTitleRound1 = CCLabelTTF::create("Round 1", "Arial", 35.0f);
	mLabelTitleRound1->setPosition(CCPoint(winSize.width / 2, winSize.height / 2 + 110));
	this->addChild(mLabelTitleRound1);

	CCLabelTTF* mLabelTitleRound2 = CCLabelTTF::create("Round 1", "Arial", 35.0f);
	mLabelTitleRound2->setPosition(CCPoint(winSize.width / 2, winSize.height / 2 + 30));
	this->addChild(mLabelTitleRound2);

	CCLabelTTF* mLabelTitleRound3 = CCLabelTTF::create("Round 1", "Arial", 35.0f);
	mLabelTitleRound3->setPosition(CCPoint(winSize.width / 2, winSize.height / 2 - 50));	
	this->addChild(mLabelTitleRound3);

	mLabelScoreRound[0] = CCLabelTTF::create("- VS -", "Arial", 25.0f);
	mLabelScoreRound[0]->setPosition(CCPoint(winSize.width / 2, winSize.height / 2 + 70));
	this->addChild(mLabelScoreRound[0]);

	mLabelScoreRound[1] = CCLabelTTF::create("- VS -", "Arial", 25.0f);
	mLabelScoreRound[1]->setPosition(CCPoint(winSize.width / 2, winSize.height / 2 - 10));
	this->addChild(mLabelScoreRound[1]);

	mLabelScoreRound[2] = CCLabelTTF::create("- VS -", "Arial", 25.0f);
	mLabelScoreRound[2]->setPosition(CCPoint(winSize.width / 2, winSize.height / 2 - 90));
	this->addChild(mLabelScoreRound[2]);

	mLabelResult = CCLabelTTF::create("", "Arial", 30.0f);
	mLabelResult->setColor(ccRED);
	mLabelResult->setPosition(CCPoint(winSize.width / 2, winSize.height / 2 - 120));
	this->addChild(mLabelResult);	

    return true;
}

void RoundSummaryView::playGameCallback(CCObject* pSender)
{
	Game* game = GameManager::getInstance().getCurrentGame();
	assert(game);

	if(!((game->curRound - 1) < (int)game->letters.size()) || (game->letters.size() == 0))
	{
		assert(0);
	}

	// switch to play Scene
	CCScene* pScene = new CCScene();
	pScene->autorelease();

	PlayScene* playScene = PlayScene::create();
	playScene->setLayerLetters(0, game->letters[game->curRound - 1]);

	pScene->addChild(playScene);

	CCTransitionFade * transitionScene = CCTransitionFade::create( 1.0f, pScene, ccWHITE );
	CCDirector::sharedDirector()->replaceScene(transitionScene);
}

void RoundSummaryView::updateResults(float delta)
{
	unschedule(schedule_selector(RoundSummaryView::updateResults));

	char szBuff[10] = {"\0"}; 

	GameManager& gameManger = GameManager::getInstance();

	std::map<std::string, std::string> paraList;
	paraList.insert(std::make_pair("gameCookie", gameManger.mCurrentGameCookie));
	paraList.insert(std::make_pair("yourCookie", gameManger.mPlayerCookie));

	NetworkManager::getInstance()->call(
		"UpdateResult"
		,this
		,callfuncO_selector(RoundSummaryView::onUpdateResultsSucceed)
		,callfuncO_selector(RoundSummaryView::onUpdateResultsFailed)
		,&paraList
		);
}

void RoundSummaryView::onUpdateResultsSucceed(CCObject* param)
{
	JsonObject* pJson = dynamic_cast<JsonObject*>(param);
	CCAssert( pJson ,"invalid type!");
	if( pJson )
	{
		Json::Value& jsonval = pJson->getJsonVal();
		int msgType = jsonval["msgType"].asInt();		

		if(msgType == Msg::GameUpdate)
		{
			if(jsonval.has("msgContent"))
			{
				Json::Value& contentJsonval = jsonval["msgContent"];

				bool bFinished = contentJsonval["finished"].asInt() != 0;

				std::string& gameCookie = contentJsonval["gameCookie"].asString();

				GameManager& gameManger = GameManager::getInstance();
				Game* game = gameManger.getCurrentGame();

				assert(game);
				assert(gameCookie == game->gameCookie);

				int nCurRound = contentJsonval["curRound"].asInt();

				Json::Value& player1Jsonval = contentJsonval["player1"];
				Json::Value& player2Jsonval = contentJsonval["player2"];				

				std::string player1_name = player1Jsonval["name"].asString();
				std::string player2_name = player2Jsonval["name"].asString();				
				
				for(size_t i = 0; i < 3; i++)
				{
					char szBufStr[10] = {0};
					sprintf(szBufStr, "s%d", i+1);

					int player1Score = player1Jsonval["roundScores"][szBufStr].asInt();
					int player2Score = player2Jsonval["roundScores"][szBufStr].asInt();

					if(gameManger.mPlayerCookie == player1Jsonval["cookie"].asString())
					{
						game->scores[0][i] = player1Score;
						game->scores[1][i] = player2Score;
					}
					else
					{
						game->scores[0][i] = player2Score;
						game->scores[1][i] = player1Score;
					}
										
					std::string scoreString;
					if(game->scores[0][i] == -1)
					{
						scoreString += "-";
					}
					else
					{
						sprintf(szBufStr, "%d", game->scores[0][i]);
						scoreString += szBufStr;
					}

					scoreString += " VS ";

					if(game->scores[1][i] == -1)
					{
						scoreString += "-";
					}
					else
					{
						sprintf(szBufStr, "%d", game->scores[1][i]);
						scoreString += szBufStr;
					}

					mLabelScoreRound[i]->setString(scoreString.c_str());
				}
				
				if(bFinished)
				{
					((CCLabelTTF*)(mPlayButton->getChildByTag(0)))->setString("Finished");

					unsigned int myFinalScore = 0;
					unsigned int opponentFinalScore = 0;
					for(size_t i = 0; i < 3; i++)
					{
						myFinalScore += game->scores[0][i];
						opponentFinalScore += game->scores[1][i];
					}
					char szBufStr[10] = {0};
					std::string scoreString;

					sprintf(szBufStr, "%d", myFinalScore);
					scoreString += szBufStr;

					scoreString += " VS ";

					sprintf(szBufStr, "%d", opponentFinalScore);
					scoreString += szBufStr;

					scoreString += (myFinalScore > opponentFinalScore) ? " WIN" : (myFinalScore < opponentFinalScore) ? " FAIL" : " DRAW";

					mLabelResult->setString(scoreString.c_str());
				}
				else
				{
					if(game->curRound != nCurRound)
					{
						game->curRound = nCurRound;

						std::string& curLetters = contentJsonval["curLetters"].asString();

						game->letters.push_back(curLetters);					

						mPlayButton->setColor(ccWHITE);
						mPlayButton->setEnabled(true);
					}
					else
					{
						schedule(schedule_selector(RoundSummaryView::updateResults), 5.0f);
					}
				}				
			}
		}
	}
}

void RoundSummaryView::onUpdateResultsFailed(CCObject* param)
{

}

void RoundSummaryView::onEnterTransitionDidFinish()
{
	CCLayer::onEnterTransitionDidFinish();

	updateResults(0);
}